<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addRole(1,'0')">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addRole(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editRole(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delRole(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 放置一个弹层 用来编辑新增节点 -->
      <el-dialog title="新增权限点" :visible="showDialog" :close-on-click-modal="false" :close-on-press-escape="false" @close="btnCancel">
        <!-- 表单 -->
        <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" style="width:90%" />
          </el-form-item>
          <el-form-item label="开启">
            <el-switch
              v-model="formData.enVisible"
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" type="primary" @click="confirmHandle">确定</el-button>
            <el-button size="small" @click="btnCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'
import { getTreeData } from '@/utils'
export default {
  name: 'Permission',
  data() {
    // 自定义校验权限名称规则,同部门的权限名称不能重复
    const validName = (rules, value, callback) => {
      // 获取同部门的数据
      let newList = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        newList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      // 把数组中每一项的name值放到一个新数组中,判断当前填入的名族是否已经存在
      // 存在,抛出错误,不存在,直接放行
      newList.map(item => item.name.trim()).includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    // 不能出现重复的标识
    const validCode = (rules, value, callback) => {
      // 简化后的数据列表
      let newList = this.originList
      if (this.isEdit) {
        newList = this.originList.filter(item => item.id !== this.formData.id)
      }
      // 把数组中每一项的code值放到一个新数组中,判断当前填入的code是否已经存在
      // 存在,抛出错误,不存在,直接放行
      newList.map(item => item.code.trim()).includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    return {
      permissionList: [], // 获取权限列表
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: { // 表单校验规则
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      isEdit: false, // 是否为编辑状态
      originList: []// 简化后的权限内列表
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取权限列表
    async  getPermissionList() {
      const res = await getPermissionList()
      // this.permissionList = res.data
      this.permissionList = getTreeData(res.data, '0')
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name, code }))
    },
    // 添加权限
    addRole(type, pid) {
      this.isEdit = false
      this.showDialog = true
      this.formData.type = type
      this.formData.pid = pid
    },
    // 编辑 权限
    async editRole(id) {
      this.isEdit = true
      this.showDialog = true
      const res = await getPermissionDetail(id)
      this.formData = res.data
    },
    // 删除权限
    delRole(id) {
      // 出现确认弹框
      this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        await delPermission(id)
        this.getPermissionList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 关闭弹窗,触发事件
    btnCancel() {
      // 弹窗关闭
      this.showDialog = false
      this.isEdit = false
      // 重置表单
      this.$refs.perForm.resetFields()
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
    },
    // 点击确定按钮
    confirmHandle() {
      // 先进行兜底验证
      this.$refs.perForm.validate(async bool => {
        if (!bool) return
        // 判断是否为编辑状态
        if (this.isEdit) {
          // 调用接口
          await updatePermission(this.formData)
        } else {
          await addPermission(this.formData)
        }
        // 弹窗关闭
        this.showDialog = false
        this.isEdit = false
        this.getPermissionList()
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
